// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import FastClick from 'fastclick'
import VueRouter from 'vue-router'
import router from './router'
import App from './App'
import {AjaxPlugin, LoadingPlugin, ToastPlugin, ConfirmPlugin, AlertPlugin} from 'vux'

Vue.use(AjaxPlugin)
// loading toast
Vue.use(LoadingPlugin)
Vue.use(ToastPlugin)
Vue.use(ConfirmPlugin)
Vue.use(AlertPlugin)
Vue.use(VueRouter)

// // baseURL
// Vue.http.defaults.baseURL = 'http://website.cloudlinker.cn/api'

// http request 拦截器
Vue.http.interceptors.request.use(
  config => {
    Vue.$vux.loading.show()
    if (localStorage.getItem('token')) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers.Authorization = localStorage.getItem('token')
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
Vue.http.interceptors.response.use(
  response => {
    Vue.$vux.loading.hide()
    return response
  },
  error => {
    Vue.$vux.loading.hide()
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data)
      Vue.$vux.toast.text(error.response.data.error)
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request)
      Vue.$vux.toast.text(error.request)
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message)
      Vue.$vux.toast.text(error.message)
    }
    return Promise.reject(error.response.data)   // 返回接口返回的错误信息
  }
)

FastClick.attach(document.body)

Vue.config.productionTip = false

router.beforeEach((to, from, next) => {
  let queryTemp = {}
  const url = to.query.url
  url ? queryTemp.url = url : null
  if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
    const user = localStorage.getItem('USER') ? JSON.parse(localStorage.getItem('USER')) : null // 本地存储user
    let token = localStorage.getItem('token') ? localStorage.getItem('token') : null // 本地存储token
    // 无token
    if (!token) {
      // 是否已授权
      if (user) {
        // 已授权
        if (user.phone) {
          // 登录过手机号
          Vue.http.post('/api/oauth/token', {
            username: user.phone,
            password: '123456',
            grant_type: 'password',
            client_id: '2',
            client_secret: 'tJj751OklqlbfI95pjpLMH7aAQFVb5H2Qhs6xgiR',
            scope: '*'
          }).then((r) => {
            localStorage.setItem('token', r.data.token_type + ' ' + r.data.access_token)
            next()
          })
        } else {
          router.push({path: 'register', query: queryTemp})
        }
      } else {
        // 未授权
        window.location.href = '/api/wechat/login?url='+ encodeURIComponent('/hz-park/#/' + url)
      }
    } else {
      next()
    }
  } else {
    next()
  }
})

/* eslint-disable no-new */
new Vue({
  router,
  render: h => h(App)
}).$mount('#app-box')
